<?php

namespace app\common\middleware;

use app\common\exception\RuntimeException;
use app\common\menu\Common;
use app\common\service\Redis;

class BaseMiddleware
{
    public function handle($request, \Closure $next)
    {
        $ip = request()->ip();
        //$maliciousIpInfo = Redis::getRedis()->hGet('pull_black_ip', $ip);
        //if ($maliciousIpInfo !== false) {
        //    throw new RuntimeException(['msg' => '您已被拉黑，请勿再次请求']);
        //}

        $number = Redis::getRedis()->get('request_record_ip:'.$ip);
        if ($number === false) {
            Redis::getRedis()->set('request_record_ip:'.$ip, 1, ['nx', 'ex' => Common::IP_MAX_FREQUENCY_SECONDS]);
        } elseif ($number !== false && $number >= Common::IP_MAX_FREQUENCY_NUMBER) {
            //if ($number >= Common::IP_MAX_PULL_BLACK_NUMBER) {
            //    Redis::getRedis()->hSet('pull_black_ip', $ip, NOW_TIME);
            //}
            Redis::getRedis()->incr('request_record_ip:'.$ip);
            throw new RuntimeException(['msg' => '请求频率过高，请稍后再试']);
        } else {
            Redis::getRedis()->incr('request_record_ip:'.$ip);
        }

        return $next($request);
    }

    public function end(\think\Response $response): void
    {
        // 回调行为
    }
}